<template>
  <div class="task-edit-view">
    <AppHeader title="修改任务">
      <template #left>
        <el-button circle @click="router.back()">
          <el-icon><ArrowLeft /></el-icon>
        </el-button>
      </template>
    </AppHeader>
    
    <el-form v-if="task" :model="task" label-width="100px" class="task-edit-form">
      <el-form-item label="任务标题" required>
        <el-input v-model="task.title"></el-input>
      </el-form-item>
      <el-form-item label="任务描述">
        <el-input type="textarea" v-model="task.description"></el-input>
      </el-form-item>
      <el-form-item label="预期完成时间">
        <el-date-picker 
          v-model="task.expectTime" 
          type="datetime"
          format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss"
          placeholder="选择日期和时间"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="优先级" required>
        <el-select v-model="task.level" placeholder="选择优先级">
          <el-option label="重要且紧急" :value="1"></el-option>
          <el-option label="重要不紧急" :value="2"></el-option>
          <el-option label="不重要但紧急" :value="3"></el-option>
          <el-option label="不重要不紧急" :value="4"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="状态" required>
        <el-select v-model="task.status" placeholder="选择状态">
          <el-option label="待办" :value="1"></el-option>
          <el-option label="已完成" :value="2"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSaveTask">保存修改</el-button>
        <el-button @click="router.back()">取消</el-button>
        <el-button type="danger" @click="handleDeleteTask">删除任务</el-button>
      </el-form-item>
    </el-form>
    <p v-else>正在加载任务详情...</p>

  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';
import AppHeader from '../components/AppHeader.vue';
import { ArrowLeft } from '@element-plus/icons-vue';

export default {
  name: 'TaskEditView',
  components: {
    AppHeader,
    ArrowLeft,
  },
  setup() {
    const route = useRoute();
    const router = useRouter();
    const task = ref(null);

    const fetchTaskDetails = async (id) => {
      try {
        const response = await axios.get(`/zwart/user/task/query`, {
          params: {
            taskId: id
          }
        });
        console.log('Task details response:', response.data);
        if (response.data) {
          task.value = response.data;
        } else {
          console.error('获取任务详情失败：响应数据为空');
          task.value = null; 
          ElMessage.error('获取任务详情失败');
        }
      } catch (error) {
        console.error('获取任务详情时出错:', error);
        task.value = null;
        ElMessage.error('获取任务详情时出错');
      }
    };

    const handleSaveTask = async () => {
      if (!task.value || !task.value.id) {
        console.error('任务数据未准备好或缺少ID');
        ElMessage.error('任务数据未准备好，无法保存');
        return;
      }

      try {
        const response = await axios.post('/zwart/user/task/update', task.value);
        console.log('更新任务响应:', response.data);
        if (response.data === true) {
          ElMessage.success('任务更新成功！');
          router.push({ name: 'Tasks' });
        } else {
          console.error('更新任务失败：后端返回错误', response.data);
          ElMessage.error('更新任务失败');
        }
      } catch (error) {
        console.error('更新任务时出错:', error);
        ElMessage.error('更新任务时出错');
      }
    };

    const handleDeleteTask = async () => {
      if (!task.value || !task.value.id) {
        ElMessage.error('无法删除任务：任务数据未准备好');
        return;
      }

      try {
        await ElMessageBox.confirm(
          '确定要删除这个任务吗？此操作不可恢复。',
          '删除确认',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
        );

        const response = await axios.delete('/zwart/user/task/delete', {
          params: {
            taskId: task.value.id
          }
        });
        
        if (response.status === 200) {
          ElMessage.success('任务已成功删除！');
          router.push({ name: 'Tasks' });
        } else {
          ElMessage.error('删除任务失败');
        }
      } catch (error) {
        if (error === 'cancel') {
          return;
        }
        console.error('删除任务时出错:', error);
        ElMessage.error('删除任务时出错');
      }
    };

    onMounted(() => {
      const taskId = route.params.id;
      if (taskId) {
        fetchTaskDetails(taskId);
      }
    });

    return {
      task,
      handleSaveTask,
      handleDeleteTask,
      router,
    };
  },
};
</script>

<style scoped>
.task-edit-view {
  padding: 20px;
}

.task-edit-form {
  margin-top: 20px;
  width: 90%;
  max-width: 600px;
  margin-left: auto;
  margin-right: auto;
}

.task-edit-form .el-form-item__label {
  font-size: 16px;
}

.task-edit-form .el-form-item__content .el-input__inner,
.task-edit-form .el-form-item__content .el-date-editor .el-input__inner,
.task-edit-form .el-form-item__content .el-select .el-input__inner {
  font-size: 16px;
}

.task-edit-form .el-form-item {
  margin-bottom: 15px;
}

.task-edit-form .el-form-item:nth-child(2) {
  margin-bottom: 10px;
}

.task-edit-form .el-form-item:nth-child(3) {
  margin-top: 0px;
  margin-bottom: 15px;
}

.task-edit-form .el-form-item__content .el-textarea {
  height: 200px;
  width: 100%;
}
</style> 